<template>
	<div class="report-wrapper">
		<div :id="containerEl" class="luckysheet" style="width: 100%; height: 100%"></div>
	</div>
</template>

<script setup>
import {
	showtoolbarConfig,
	sheetBaseConfig,
	reportDataBaseConfig,
	initLucksheet,
	loadLucksheetCss,
	reportTransFormateData,
} from './utils/report.js'

import { exportExcel } from './utils/export.js'

import { onMounted, onUnmounted, nextTick } from 'vue'
import printJS from 'print-js'

loadLucksheetCss()
const props = defineProps({
  containerEl: {
    type:String,
    default:'luckysheet-preview'
  },
	option: {
		type: [Object, String],
		default: () => ({}),
	},
	baseConfig: {
		type: Object,
		default: () => ({}),
	},
	hooks: {
		type: Object,
		default: () => ({}),
	},
})

const initReport = (options) => {
	const optionConfig = {
		...sheetBaseConfig({
			container: props.containerEl,
			allowEdit: false,
			allowUpdate: false,
			showsheetbar: false,
			showinfobar: false,
			showtoolbar: true,
			showtoolbarConfig: {
				...showtoolbarConfig,
				save: false,
				preview: false,
				print: true,
			},
			enableAddRow: false, //允许添加行
			enableAddBackTop: false, //允许回到顶部
			rowHeaderWidth: 0, // 不显示行标号
			columnHeaderHeight: 0, //不显示列标号
			scrollLeft: 0, //左右滚动条位置
			scrollTop: 0, //上下滚动条位置
			...props.baseConfig,
		}),
		data: [
			...reportDataBaseConfig({
				hide: 0,
				row: 36, //行数
				column: 8, //列数
				...(options || {}),
			}),
		],
		hook: {
			export: (e) => {
				exportExcel(window.luckysheet.getAllSheets(), '表格模板')
			},
			print: (e) => {
				const src = window.luckysheet.setSelectAll() // 全选获取截屏数据
				printJS({ printable: src, type: 'image' })
			},
			cellAllRenderBefore: (data, sheet) => {
				window.luckysheet.hideGridLines() //隐藏网格线
			},
			...props.hooks,
		},
	}
	window.luckysheet.create(optionConfig)
}

const initData =async (option) => {
	nextTick(() => {
		const data = typeof option == 'string' ? JSON.parse(option) : option
		let config ={}
		if (data.celldata) {
			config = reportTransFormateData(data)
		}
		initReport(config)
	})
}
onMounted(async () => {
	if (!window.luckysheet) await initLucksheet()
	nextTick(() => {
		initData(props.option)
	})
})

defineExpose({
	initData,
})

onUnmounted(() => {
	window.luckysheet.destroy()
})
</script>

<style>
.luckysheet-input-box {
	z-index: 10000000000;
}
.report-wrapper {
	width: 100%;
	height: 100vmin;
	position: relative;
}
.luckysheet {
	position: absolute;
	width: 100%;
	height: 100%;
	border: none;
}
</style>
